package com.ruoyi.web.controller.business;

import java.io.FileOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.afterturn.easypoi.word.WordExportUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.TDrugInfo;
import com.ruoyi.system.domain.TOperationQuery;
import com.ruoyi.system.domain.TPrescriptionDrugInfo;
import com.ruoyi.system.mapper.TDrugInfoMapper;
import com.ruoyi.system.service.ITDrugInfoService;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.TPrescriptionRecords;
import com.ruoyi.system.service.ITPrescriptionRecordsService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 处方信息Controller
 *
 * @author ruoyi
 * @date 2023-03-11
 */
@Controller
@RequestMapping("/system/records")
public class TPrescriptionRecordsController extends BaseController {
    private String prefix = "system/records";

    @Autowired
    private ITPrescriptionRecordsService tPrescriptionRecordsService;

    @Autowired
    private ITDrugInfoService tDrugInfoService;

    @Autowired
    private TDrugInfoMapper tDrugInfoMapper;

    @RequiresPermissions("system:records:view")
    @GetMapping()
    public String records() {
        return prefix + "/records";
    }

    /**
     * 查询处方信息列表
     */
    @RequiresPermissions("system:records:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TPrescriptionRecords tPrescriptionRecords) {
        startPage();
        if (tPrescriptionRecords.getStatus().equals("未完结")) {
            tPrescriptionRecords.setStatus("0,1,2,4");
        } else if (tPrescriptionRecords.getStatus().equals("已完结")) {
            tPrescriptionRecords.setStatus("3");
        }
//        if (tPrescriptionRecords.getSex().equals("女")){
//            tPrescriptionRecords.setSex("1");
//        }else if (tPrescriptionRecords.getSex().equals("男")){
//            tPrescriptionRecords.setSex("0");
//        }
        tPrescriptionRecords.setDoctorid(getUserId()); // 限定查询自己开的处方
        List<TPrescriptionRecords> list = tPrescriptionRecordsService.selectTPrescriptionRecordsList(tPrescriptionRecords);
        return getDataTable(list);
    }

    /**
     * 导出处方信息列表
     */
    @RequiresPermissions("system:records:export")
    @Log(title = "处方信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TPrescriptionRecords tPrescriptionRecords) {
        if (tPrescriptionRecords.getStatus().equals("未完结")) {
            tPrescriptionRecords.setStatus("0,1,2,4");
        } else if (tPrescriptionRecords.getStatus().equals("已完结")) {
            tPrescriptionRecords.setStatus("3");
        }
        tPrescriptionRecords.setDoctorid(getUserId()); // 限定查询自己开的处方
        List<TPrescriptionRecords> list = tPrescriptionRecordsService.selectTPrescriptionRecordsList(tPrescriptionRecords);
        ExcelUtil<TPrescriptionRecords> util = new ExcelUtil<TPrescriptionRecords>(TPrescriptionRecords.class);
        return util.exportExcel(list, "处方信息数据");
    }

    /**
     * 新增处方信息
     */
    @GetMapping("/add/{id}")
    public String add(@PathVariable("id") Long id, ModelMap mmap) {
        TPrescriptionRecords tPrescriptionRecords;
        if (id > 0) {
            tPrescriptionRecords = tPrescriptionRecordsService.selectTPrescriptionRecordsById(id);
            mmap.put("mode", "edit");
        } else {
            tPrescriptionRecords = new TPrescriptionRecords();
            mmap.put("mode", "add");
        }
        // 输液费
//        TDrugInfo tDrugInfo = tDrugInfoService.selectTDrugInfo("输液费");
//        mmap.put("syf", tDrugInfo);
        mmap.put("tPrescriptionRecords", tPrescriptionRecords);
        mmap.put("deptid", getSysUser().getDeptId());
        return prefix + "/add";
    }

    /**
     * 新增保存处方信息
     */
    @RequiresPermissions("system:records:add")
    @Log(title = "处方信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(TPrescriptionRecords tPrescriptionRecords) {

        List<TPrescriptionDrugInfo> tPrescriptionDrugInfoList = tPrescriptionRecords.getTPrescriptionDrugInfoList();
        for (TPrescriptionDrugInfo tPrescriptionDrugInfo : tPrescriptionDrugInfoList) {
            //判断药品数量
            TDrugInfo tDrugInfo = tDrugInfoMapper.selectTDrugInfoById(tPrescriptionDrugInfo.getDrugid());
            String drugName = tDrugInfo.getDrugName();
            if (tDrugInfo.getStock() < tPrescriptionDrugInfo.getCounts()*tPrescriptionDrugInfo.getDays()) {
                throw new BaseException("药品"+drugName+"库存数量不足！");
            }
        }
        tPrescriptionRecords.setSkinTest("");
        tPrescriptionRecords.setCrtime(DateUtils.getNowDate());
        tPrescriptionRecords.setLast_operate_time(DateUtils.getNowDate());
        tPrescriptionRecords.setStatus("1");
        tPrescriptionRecords.setDoctorid(getSysUser().getUserId());
        return toAjax(tPrescriptionRecordsService.insertTPrescriptionRecords(tPrescriptionRecords));
    }

    /**
     * 修改保存处方信息
     */
    @RequiresPermissions("system:records:edit")
    @Log(title = "处方信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TPrescriptionRecords tPrescriptionRecords) {
        tPrescriptionRecords.setStatus("1");
        tPrescriptionRecords.setLast_operate_time(DateUtils.getNowDate());
        return toAjax(tPrescriptionRecordsService.updateTPrescriptionRecords(tPrescriptionRecords));
    }

    /**
     * 删除处方信息
     */
    @RequiresPermissions("system:records:remove")
    @Log(title = "处方信息", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(tPrescriptionRecordsService.deleteTPrescriptionRecordsByIds(ids));
    }


    /**
     * 展示处方信息
     */
    @RequiresPermissions("system:records:detail")
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Long id, ModelMap mmap) {
        TPrescriptionRecords tPrescriptionRecords = tPrescriptionRecordsService.selectTPrescriptionRecordsById(id);
//        TDrugInfo tDrugInfo = tDrugInfoService.selectTDrugInfo("输液费");
//        mmap.put("syf", tDrugInfo);
        mmap.put("tPrescriptionRecords", tPrescriptionRecords);
        mmap.put("mode", "detail");
//        mmap.put("deptid", getSysUser().getDeptId());
        return prefix + "/add";
    }

    /**
     * 结算清单  姓名和创建日期必填
     */
//    @RequiresPermissions("system:records:getSettlementList")
    @PostMapping("/getSettlementList")
    @ResponseBody
    public AjaxResult getSettlementList(TPrescriptionRecords tPrescriptionRecords) {
        Map<String, Object> map = new HashMap<String, Object>();
        Date date=new Date();
        SimpleDateFormat dateFormat=new SimpleDateFormat("YYYY-MM-dd");
        String format = dateFormat.format(date);

        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = sim.format(tPrescriptionRecords.getCrtime());
        //总治疗费用
        int totalCost = tPrescriptionRecordsService.getTotalCost(tPrescriptionRecords);
        //药品明细
        List<Map<String, Object>> drugList = tPrescriptionRecordsService.getDrugList(tPrescriptionRecords);
        map.put("name",tPrescriptionRecords.getName());
        String sex = tPrescriptionRecords.getSex();
        if (sex.equals("1")){
            map.put("sex","女");
        }else if (sex.equals("0")){
            map.put("sex","男");
        }
        map.put("age",tPrescriptionRecords.getAge());
        map.put("crtime",format1);
        map.put("totalCost",totalCost);
        map.put("drugList",drugList);
        map.put("date",format);

        try {
            XWPFDocument doc = WordExportUtil.exportWord07(
                    "D:\\报表\\大连甘井子新玉胜路诊所结算清单.docx", map);
            FileOutputStream fos = new FileOutputStream("D:\\报表\\结算清单-"+tPrescriptionRecords.getName()+".docx");
            doc.write(fos);
            fos.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return toAjax(1);
    }
}
